package com.jxj.study.controller.WebClientControllers;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
/**
 * 异步调用
 */
@RestController
public class WebClientController {

    private final WebClient webClient = WebClient.builder()
            .baseUrl("http://localhost:81")
            .build();

    @GetMapping("/test")
    public void test() {
        System.out.println("--- begin ---");

        // 需要提交的 json 字符串
        String jsonStr = "{userId: 222,title: abc,body: 航歌}";

        //Flux bodyToFlux
        Mono<String> mono = webClient
                .post() // POST 请求
                .uri("/map")  // 请求路径
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(jsonStr))
                .retrieve() // 获取响应体
                .bodyToMono(String.class); //响应数据类型转换

        // 订阅（异步处理结果）
        mono.subscribe(System.out::println);

        System.out.println("--- end ---"+mono.block());
//        mono.block(Duration.ofSeconds(3)); //阻塞式 同步
        System.out.println("--- end ---"+mono.block());
    }
}